package com.jucai.pppeiyouclient.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseApplication;
import com.jucai.pppeiyouclient.bean.IMUserBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.StringUtil;
import com.jucai.pppeiyouclient.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

public class ConversationActivity extends FragmentActivity implements View.OnClickListener {

    private static final String TAG = "ConversationActivity : ";

    private String focusString;

    private TextView followTextView;
    private String mTargetId;
    private String strTitle;

    private ConversationFragment fragment;
    /**
     * 刚刚创建完讨论组后获得讨论组的id 为targetIds，需要根据 为targetIds 获取 targetId
     */
    private String mTargetIds;

    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation);
        String nickName = getIntent().getData().getQueryParameter("title");
        LogUtils.e("nickName:" + nickName);
        ((TextView) findViewById(R.id.common_title_text)).setText(nickName);
        followTextView = (TextView) findViewById(R.id.common_follow);
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_follow).setOnClickListener(this);
        focusString = SharedPreferencesUtil.getStringPreference(ConversationActivity.this, "rongyun", "rongyun_isfocus", "0");

        if (focusString.equals("1")) {
            followTextView.setText("已关注");
        } else {
            followTextView.setText("关注");
        }
        getIntentDate(getIntent());
        isReconnect(getIntent());
    }


    /**
     * 展示如何从 Intent 中得到 融云会话页面传递的 Uri
     */
    private void getIntentDate(Intent intent) {

        mTargetId = intent.getData().getQueryParameter("targetId");
        mTargetIds = intent.getData().getQueryParameter("targetIds");
        //intent.getData().getLastPathSegment();//获得当前会话类型
        mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        strTitle = intent.getData().getQueryParameter("title");
        enterFragment(mConversationType, mTargetId);

        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            @Override
            public UserInfo getUserInfo(String userId) {
                if (!StringUtil.isChinese(userId))
                    getFriendUserInfo(userId, true);
                return null;//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
            }

        }, true);

        getFriendUserInfo(BaseApplication.targetMemberId, false);

    }

    private void getFriendUserInfo(String userId, boolean isRongId) {
        Map<String, String> mapWallet = new HashMap<>();
        if (isRongId) {
            mapWallet.put("service", "Public_Chat.getMemberChatData");
            mapWallet.put("target_member_id", userId);
        } else {
            mapWallet.put("service", "Public_Chat.getMemberChatId");
            mapWallet.put("target_member_id", userId);
        }

        CommonRequestNetData.getJsonStringDataByEncrpt(ConversationActivity.this, mapWallet, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) {
                try {

                    IMUserBean dataBean = new Gson().fromJson(str, IMUserBean.class);
                    RongIM.getInstance().refreshUserInfoCache(new UserInfo(dataBean.rongyun_id, dataBean.rongyun_nickname, Uri.parse(dataBean.rongyun_avatar)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String str) {
                LogUtils.e("jsonObject：" + str);
            }

        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;
            case R.id.common_follow:
                if (focusString.equals("1")) {
                    ToastUtils.showToast("您已经关注过对方了");
                    return;
                }
                HashMap<String, String> param = new HashMap<>();
                param.put("service", "Public_Chat.addFocus");
                param.put("target_member_id", BaseApplication.targetMemberId);
                param.put("member_id", LoginUtils.getMember_id(ConversationActivity.this));
                LogUtils.e("param = " + param.toString());

                CommonRequestNetData.getJsonObjectData(ConversationActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
                    @Override
                    public void parseJsonObject(JSONObject jsonObject) {
                        LogUtils.e(TAG + "jsObj = " + jsonObject);
                        followTextView.setText("已关注");
                        focusString = "1";
                    }
                });
                break;
        }
    }

    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType
     * @param mTargetId
     */
    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        if (fragment == null) {
            fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);

            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                    .appendQueryParameter("targetId", mTargetId).build();

            fragment.setUri(uri);
        }
    }

    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect(Intent intent) {


        String token = LoginUtils.getRongyun_token(this);


        //push或通知过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {

            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {

                    reconnect(token);
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            }
        }
    }

    /**
     * 重连
     *
     * @param token
     */
    private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(BaseApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {
                    RongIM.getInstance().setCurrentUserInfo(new UserInfo(LoginUtils.getRongyun_id(ConversationActivity.this), LoginUtils.getMember_nickname(ConversationActivity.this), Uri.parse(LoginUtils.getMember_avatar(ConversationActivity.this))));
                    enterFragment(mConversationType, mTargetId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

}
